import 'package:flutter/material.dart';
import 'package:get/get.dart';

import '../../../../models/category_model.dart';
import 'logic.dart';

class FoodManagementPage extends StatelessWidget {
  final FoodManagementLogic logic = Get.put(FoodManagementLogic());

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('菜品管理'),
        backgroundColor: Color(0xFFBE9650),
        foregroundColor: Colors.white,
      ),
      body: Obx(() {
        if (logic.isLoading.value) {
          return Center(child: CircularProgressIndicator());
        }

        if (logic.isEditing.value) {
          return _buildEditForm();
        }

        return _buildFoodList();
      }),
      floatingActionButton: Obx(() {
        if (!logic.isEditing.value) {
          return FloatingActionButton(
            onPressed: logic.addFood,
            backgroundColor: Color(0xFFBE9650),
            child: Icon(Icons.add),
          );
        }
        return SizedBox.shrink();
      }),
    );
  }

  Widget _buildFoodList() {
    if (logic.foods.isEmpty) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(Icons.no_food, size: 64, color: Colors.grey),
            SizedBox(height: 16),
            Text('暂无菜品', style: TextStyle(fontSize: 18, color: Colors.grey)),
            SizedBox(height: 24),
            ElevatedButton(
              onPressed: logic.addFood,
              style: ElevatedButton.styleFrom(
                backgroundColor: Color(0xFFBE9650),
                foregroundColor: Colors.white,
              ),
              child: Text('添加菜品'),
            ),
          ],
        ),
      );
    }

    return RefreshIndicator(
      onRefresh: logic.loadData,
      child: ListView.builder(
        padding: EdgeInsets.all(16),
        itemCount: logic.foods.length,
        itemBuilder: (context, index) {
          final food = logic.foods[index];
          final category = logic.categories.firstWhere(
            (c) => c.id == food.categoryId,
            orElse: () => Category(id: -1, name: '未知分类'),
          );

          return Card(
            margin: EdgeInsets.only(bottom: 16),
            elevation: 2,
            child: Padding(
              padding: EdgeInsets.all(16),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // 菜品图片
                  ClipRRect(
                    borderRadius: BorderRadius.circular(8),
                    child: Image.network(
                      food.image,
                      width: 100,
                      height: 100,
                      fit: BoxFit.cover,
                      errorBuilder: (context, error, stackTrace) {
                        return Container(
                          width: 100,
                          height: 100,
                          color: Colors.grey[300],
                          child: Icon(Icons.broken_image, color: Colors.grey[600]),
                        );
                      },
                    ),
                  ),
                  SizedBox(width: 16),
                  // 菜品信息
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          food.name,
                          style: TextStyle(
                            fontSize: 18,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                        SizedBox(height: 4),
                        Text(
                          '分类: ${category.name}',
                          style: TextStyle(color: Colors.grey[600]),
                        ),
                        SizedBox(height: 4),
                        Text(
                          '价格: ¥${food.price.toStringAsFixed(2)}',
                          style: TextStyle(
                            color: Color(0xFFBE9650),
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                        SizedBox(height: 4),
                        Text(
                          food.description,
                          maxLines: 2,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(fontSize: 14),
                        ),
                      ],
                    ),
                  ),
                  // 操作按钮
                  Column(
                    children: [
                      IconButton(
                        icon: Icon(Icons.edit, color: Colors.blue),
                        onPressed: () => logic.editFood(food),
                      ),
                      IconButton(
                        icon: Icon(Icons.delete, color: Colors.red),
                        onPressed: () => logic.deleteFood(food),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          );
        },
      ),
    );
  }

  Widget _buildEditForm() {
    final isNewFood = logic.editingFood.value == null;
    
    return SingleChildScrollView(
      padding: EdgeInsets.all(16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            isNewFood ? '添加菜品' : '编辑菜品',
            style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
          ),
          SizedBox(height: 24),
          
          // 菜品名称
          TextField(
            controller: logic.nameController,
            decoration: InputDecoration(
              labelText: '菜品名称',
              border: OutlineInputBorder(),
              prefixIcon: Icon(Icons.restaurant_menu),
            ),
          ),
          SizedBox(height: 16),
          
          // 菜品分类
          Obx(() => DropdownButtonFormField<int>(
            value: logic.selectedCategoryId.value,
            decoration: InputDecoration(
              labelText: '菜品分类',
              border: OutlineInputBorder(),
              prefixIcon: Icon(Icons.category),
            ),
            items: logic.categories.map((category) {
              return DropdownMenuItem(
                value: category.id,
                child: Text(category.name),
              );
            }).toList(),
            onChanged: (value) {
              logic.selectedCategoryId.value = value;
            },
          )),
          SizedBox(height: 16),
          
          // 菜品价格
          TextField(
            controller: logic.priceController,
            keyboardType: TextInputType.numberWithOptions(decimal: true),
            decoration: InputDecoration(
              labelText: '菜品价格',
              border: OutlineInputBorder(),
              prefixIcon: Icon(Icons.attach_money),
            ),
          ),
          SizedBox(height: 16),
          
          // 菜品图片
          TextField(
            controller: logic.imageController,
            decoration: InputDecoration(
              labelText: '菜品图片URL',
              border: OutlineInputBorder(),
              prefixIcon: Icon(Icons.image),
            ),
          ),
          SizedBox(height: 16),
          
          // 菜品描述
          TextField(
            controller: logic.descriptionController,
            maxLines: 3,
            decoration: InputDecoration(
              labelText: '菜品描述',
              border: OutlineInputBorder(),
              prefixIcon: Icon(Icons.description),
              alignLabelWithHint: true,
            ),
          ),
          SizedBox(height: 24),
          
          // 按钮
          Row(
            mainAxisAlignment: MainAxisAlignment.end,
            children: [
              OutlinedButton(
                onPressed: logic.cancelEdit,
                child: Text('取消'),
                style: OutlinedButton.styleFrom(
                  padding: EdgeInsets.symmetric(horizontal: 24, vertical: 12),
                ),
              ),
              SizedBox(width: 16),
              ElevatedButton(
                onPressed: logic.saveFood,
                child: Text('保存'),
                style: ElevatedButton.styleFrom(
                  backgroundColor: Color(0xFFBE9650),
                  foregroundColor: Colors.white,
                  padding: EdgeInsets.symmetric(horizontal: 24, vertical: 12),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }
}
